package com.zmx.user.service;

import com.alibaba.fastjson.JSONArray;
import com.zmx.common.common.exception.BusinessException;
import com.zmx.common.common.invocation.InvocationInfoProxy;
import com.zmx.common.common.service.BaseService;
import com.zmx.product.api.ProductApi;
import com.zmx.product.dto.ProductDto;
import com.zmx.user.dto.MemberCommentsDto;
import com.zmx.user.entity.MemberComments;
import com.zmx.user.repository.MemberCommentsRepository;
import com.zmx.user.service.mapper.MemberCommentsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhaomxr
 */
@Service
public class MemberCommentsService extends BaseService<MemberComments, MemberCommentsDto, MemberCommentsRepository, MemberCommentsMapper> {

    @Autowired
    private ProductApi productApi;

    public Page getCommentsByPage(Long productId, Integer pageIndex, Integer pageSize) {
        //根据商品id级联查询该商品所有同规格商品id
        List<ProductDto> productDtos = productApi.getProductListByProductSn(productId);

        List<Long> productIds = productDtos.stream().map(ProductDto::getId).collect(Collectors.toList());
        Map<String, Object> params = new HashMap<String, Object>(2);
        params.put("productId_in", productIds);
        params.put("createTime_sort", Sort.Direction.DESC);

        Page<MemberCommentsDto> page = this.getAll(params, pageIndex, pageSize);
        for (MemberCommentsDto commentsDto : page.getContent()) {
            //初始化评论上传图片List
            if (!StringUtils.isEmpty(commentsDto.getDetailPics())) {
                List<String> detailPicsList = JSONArray.parseArray(commentsDto.getDetailPics(), String.class);
                commentsDto.setDetailPicsList(detailPicsList);
            }
        }

        return page;
    }

    public void addComments(MemberCommentsDto memberCommentsDto) {
        Long memberId = Long.valueOf(InvocationInfoProxy.getUserId());
        //同一个人每天评论次数不能超过20次
        int count = repository.countByMemberIdToDay(memberId);
        if (count > 50) {
            throw new BusinessException("当天评论次数不能超过50次");
        }

        memberCommentsDto.setMemberId(memberId);
        memberCommentsDto.setIsVaild(1);
        this.create(memberCommentsDto);
    }
}
